<template>
  <div>
    <!-- 手机号码、
        昵称、
        真实姓名、
        邮箱地址、
        密码和确认密码 -->
    <div class="content">
        <div class="title">
        <span>{{ title }}</span>
        <span @click="backToLogin()">
            <el-icon>
            <ArrowLeftBold />
            </el-icon>
            <span>返回登录</span>
        </span>
        </div>

        <div class="main">
            
            <el-form :rules="userFormRules" class="form-code" ref="ruleFormRef" label-width="100px" :model="form" size="large" >
                <el-row>
                    <el-col :span="10">
                        <el-form-item prop="nickName">
                            <el-input v-model="form.nickName" placeholder="请输入您的昵称"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="14">
                    <el-form-item prop="name">
                        <el-input v-model="form.name" placeholder="请输入您的真实姓名"/>
                    </el-form-item>
                      <!-- <el-form-item>
                        <el-button-group>
                          <el-button :disabled="codeType" @click="codeShow = true" :type="codeShow?'primary':''">手机验证</el-button>
                          <el-button :disabled="codeType" @click="codeShow = false" :type="!codeShow?'primary':''">邮箱验证</el-button>
                        </el-button-group>
                      </el-form-item> -->
                    </el-col>
                </el-row>
                
                <el-row>
                  <el-col :span="10">
                    <el-form-item prop="password">
                            <el-input v-model="form.password" show-password  placeholder="请输入您的密码"/>
                        </el-form-item>
                  </el-col>
                  <el-col :span="14">
                        <el-form-item prop="phone">
                            <el-input v-model="form.phone"  placeholder="请输入联系电话">
                                <!-- <template #append v-if="codeShow">
                                    <span class="getCode" @click="getCode(true)">{{codeText}}</span>
                                </template> -->
                            </el-input>
                        </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                    <el-col :span="10">
                      <el-form-item prop="quirePassword">
                            <el-input v-model="form.quirePassword" show-password  placeholder="请确认您的密码"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="14">
                        <el-form-item prop="email">
                            <el-input v-model="form.email" placeholder="请输入邮箱">
                                <!-- <template #append v-if="!codeShow">
                                    <span class="getCode" @click="getCode(false)">{{codeText}}</span>
                                </template> -->
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                
                <el-row>
                    <el-col :span="10">
                    </el-col>
                    <el-col :span="8">
                        <!-- <el-form-item prop="phone">
                            <el-input v-model="form.code"  placeholder="请输入验证码">
                            </el-input>
                        </el-form-item> -->
                    </el-col>
                </el-row>
            </el-form>

        </div>
        
        <div style="display: flex;justify-content: center;">
            <el-button @click="registerUser(ruleFormRef)" style="width: 320px; margin-top: 30px">注册用户</el-button>
        </div>
    </div>

  </div>
</template>

<script setup lang="ts">
///////////////////////////////// 引入区 · 开始 ////////////////////////////////////////
import { reactive, ref, computed} from "vue";
import type { FormInstance,FormRules } from 'element-plus'
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import { sendValidateCode ,sendEmailValidateCode,registerUserInfo } from "@/api/user";
import store from "@/stores/index";

///////////////////////////////// 引入区 · 结束 ////////////////////////////////////////
///////////////////////////////// 接口区 · 开始 ////////////////////////////////////////

interface formType {
    phone: string,
    nickName: string,
    name: string,
    email: string,
    password: string,
    quirePassword: string,
    code: string,
    avatar: string,
    codeShow: boolean
}

interface Props {
  title: string
}
interface RuleForm {
    name: string,
    phone: string,
    nickName: string,
    email: string,
    password: string,
    quirePassword: string,
    code: string,
}
///////////////////////////////// 接口区 · 结束 ////////////////////////////////////////
///////////////////////////////// 变量区 · 开始 ////////////////////////////////////////
defineProps<Props>();
const ruleFormRef = ref<FormInstance>()
const router = useRouter();
const form = reactive<formType>({
  name: "",
  phone: "",
  nickName: "",
  email: "",
  password: "",
  code: "",
  quirePassword: "",
  avatar: "",
  codeShow: true
})
const userFormRules = reactive<FormRules<RuleForm>>({
    nickName: { required: true, message: '请输入昵称', trigger: 'blur' },
    name : { required: true, message: '请输入真实名称', trigger: 'blur' },
    password : [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, max: 12, message: '密码字符长度在6-12位', trigger: ['blur'] }
    ],
    quirePassword : [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, max: 12, message: '密码字符长度在6-12位', trigger: ['blur'] }
    ],
})
const codeText = ref<string>("获取验证码")
const codeType = ref<boolean>(false)

/**
 * 获取验证码显示；当存在手机和邮箱同时填写时，手机获取验证码优先
 */
const codeShow = ref<boolean>(true)


///////////////////////////////// 变量区 · 结束 ////////////////////////////////////////
///////////////////////////////// 方法定义区 · 开始 ////////////////////////////////////////
const backToLogin = (): void => {
  router.push({ path: '/login', query: { isReg: false}})
}

///////////////////////////////// 方法定义区 · 结束 ////////////////////////////////////////
///////////////////////////////// 请求区 · 开始 ////////////////////////////////////////
const registerUser = (formEl: FormInstance | undefined)=>{
  if(form.phone == "" && form.email == ""){
    ElMessage.error("联系电话和邮箱必须填写其中一项！")
    return
  }
  
  if(form.phone != "" && !store().validityPhone(form.phone)){
    ElMessage.error("手机号格式输入不正确！")
    return
  }else if(form.email != "" && !store().validityEmail(form.email)){
      ElMessage.error("邮箱格式输入不正确！")
      return
  }
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      // 注册
      form.codeShow = codeShow.value
      form.avatar = "https://himg.bdimg.com/sys/portrait/item/public.1.ba5cd65e.C9LpYCQo75G2YAAJzH4Q2Q.jpg"
      let rep = await registerUserInfo(form);
      if(rep.data.code != 200){
        ElMessage.error(rep.data.msg)
      }else{
        ElMessage.success("注册成功！稍后为您跳转至登录页面~");
        // 登录成功，跳转
        setTimeout(()=>{backToLogin()},2000)
      }
    } else {
      ElMessage.error("请确认表单数据是否填写完毕或格式正确！")
    }
  })
}
const timerStart = ref<boolean>(true)
// 记录选择注册的方式；true：手机号；false：邮箱
const sendMethodRef = ref<boolean>(true)
/**
 * 获得验证码存入redis
 * @param sendMethod 区分电话和邮箱
 */
const getCode = async (sendMethod:boolean)=>{

  let res;
  sendMethodRef.value = sendMethod
  if (sendMethod) {
    // 手机
    if(form.phone ==""){
      ElMessage.error("请输入手机号！")
      return
    }
    if(!store().validityPhone(form.phone)){
      ElMessage.error("手机号格式输入不正确！")
      return
    }
    res = await sendValidateCode(form.phone);
  }else{
    // 邮箱
    if(form.email ==""){
      ElMessage.error("请输入邮箱！")
      return
    }
    if(!store().validityEmail(form.email)){
      ElMessage.error("邮箱格式输入不正确！")
      return
    }
    res = await sendEmailValidateCode(form.email);
  }

  if (res.data.code === 200) {
    codeType.value = true
    // 开启倒计时
    let num = 60
    if(timerStart.value){
      timerStart.value = false
      codeText.value = num+"s 后再次获取"
      let a = setInterval(()=>{
        if(num==0){
          num = 60
          timerStart.value = true
          codeType.value = false
          codeText.value = "获取验证码"
          clearInterval(a)
          return
        }
        timerStart.value = false
        num--
        codeText.value = num+"s 后再次获取"
      },1000)
    }else{
      return
    }
    ElMessage({ message: res.data.msg, type: "success" });
    return
  }else{
    ElMessage({ message: res.data.msg, type: "error" });
  }
}


///////////////////////////////// 请求区 · 结束 ////////////////////////////////////////

</script>

<style lang="scss" scoped>

.form-code {
  position: relative;
  :deep(.el-form-item--large){
    margin-bottom: 0px;
  }
  :deep(.el-form-item__content) {
    div:nth-child(1) {
      margin-top: 20px;
    }

    div:nth-child(2) {
      div:nth-child(1) {
        padding-right: 100px;
      }
    }
  }

  
  :deep(.el-form-item--large .el-form-item__content){
    margin-left: 40px !important;
  }


  :deep(.el-form-item__content div:nth-child(1) .el-input__wrapper) {
    padding-left: 10px;
    margin-top: 0;
  }

  .get-code-btn {
    position: absolute;
    left: 217px;
    top: 111px;
    z-index: 999;
    font-size: 12px;
    cursor: pointer;
    color: $main-color;
  }
}
.getCode{
    cursor: pointer;
}
.main{
    margin-top: 50px;
}
// ::v-deep .el-form-item__label{
//     width: 90px;
// }
.content {
  padding: 10px 20px 40px;
  overflow: hidden;

  .title {
    display: flex;
    justify-content: space-between;
    padding-bottom: 10px;
    font-family: MicrosoftYaHei-Bold;
    font-size: 20px;
    color: #2C2E40;
    font-weight: 700;

    span:nth-child(2) {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-family: MicrosoftYaHeiUI;
      font-size: 14px;
      color: #31363F;
      font-weight: 400;
      cursor: pointer;

      span {
        padding: 0 4px;
      }
    }
  }

  .form-code {
    position: relative;

    :deep(.el-form-item__content) {

      div:nth-child(1) {
        margin-top: 30px;
      }

      div:nth-child(2) {
        div:nth-child(1) {
          padding-right: 100px;
        }
      }
    }

    :deep(.el-form-item__content div:nth-child(1) .el-input__wrapper) {
      padding-left: 10px;
      margin-top: 0;
    }

    .get-code-btn {
      position: absolute;
      left: 217px;
      top: 111px;
      z-index: 999;
      font-size: 12px;
      cursor: pointer;
      color: $main-color;
    }
  }


  .form-btn {
    margin-top: 50px;
  }
}

</style>